import Cookies from 'js-cookie'
import {defineAsyncComponent} from "vue";
import {CACHE_START_STRING} from "@/constants/data";
import areaList from "@/constants/area"

export const localCache = {
    setCache(key: string, value: unknown) {
        localStorage.setItem(CACHE_START_STRING + key, JSON.stringify(value))
    },
    getCache(key: string) {
        const result = localStorage.getItem(CACHE_START_STRING + key)
        if (result !== null) {
            return JSON.parse(result);
        } else {
            return ""
        }
    },
    clear() {
        localStorage.clear()
    }
}
export const cookieCache = {
    setCache(key: string, value: unknown, expires?: number) {
        if (expires) {
            Cookies.set(key, value, {
                expires
            })
        } else {
            Cookies.set(key, value)
        }
    },
    getCache(key: string) {
        return Cookies.get(key);
    }
}

// 获取异步组件
export const getAsyncComponent = (path: string) => {
    return defineAsyncComponent(() => import(/* @vite-ignore */path))
}
/**
 * @param downloadAttr {string} 下载后的名字
 * @param hrefAttr {string} 文件地址
 */
export const downloadFile = (downloadAttr: string, hrefAttr: string) => {
    const aWrapper = document.createElement("a");
    aWrapper.download = downloadAttr
    aWrapper.href = hrefAttr
    aWrapper.click()
    document.body.appendChild(aWrapper)
}

// 获取格式化后的地址, split_word:间隔符号
export const getWholeAddress = (provinceId: number = 0, cityId: number = 0, districtId: number = 0, detailArea: string = "", split_word = "") => {
    const {
        province_list,
        city_list,
        county_list
    } = areaList
    const province = province_list[provinceId]
    const city = city_list[cityId]
    const district = county_list[districtId]
    const wholeAddress = [province, city, district, detailArea]
    return wholeAddress.join(split_word)
}

// 判断是否
export const getCanChooseSpec = (chooseSpec: any, sysProductSpecsVoList: any) => {
    if (!sysProductSpecsVoList.length) return false
    const {productSpecs} = sysProductSpecsVoList[0]
    const keys = Object.keys(productSpecs)
    // 列表循环
    for (let item of sysProductSpecsVoList) {
        let isAllCompare = true
        // 记录循环，只要记录的东西和我现在选取的东西一致，那么就是可以的，因为只返回了有库存的
        for (let key of keys) {
            if (chooseSpec[key] !== item.productSpecs[key]) {
                isAllCompare = false
            }
        }
        if (isAllCompare) {
            return item
        }
    }
    return false
}
// 付款后跳转的页面
export const handleToPage = (payPageScript: string) => {
    const wantPageUrl = payPageScript.substring(8, payPageScript.length - 9)
    const oScript = document.createElement("script")
    oScript.innerHTML = wantPageUrl
    document.body.appendChild(oScript)
}

// 判断是否已经登录
export const checkIsLogin = () => {
    const token = localCache.getCache("token")
    return !!token
}
